package com.jxtc.enterprise.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.jxtc.enterprise.admin.dto.AdminLoginDTO;
import com.jxtc.enterprise.admin.service.AdminLoginService;
import com.jxtc.enterprise.admin.vo.AdminLoginSuccessVO;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/jxtc/enterprise/admin")
@RequiredArgsConstructor
@Slf4j
public class AdminLoginController {

    private final AdminLoginService adminLoginService;
    private final RedisTemplate<String, Object> redisTemplate;

    @ApiResponse(responseCode = "200", description = "登录成功时，code 返回 200， data 返回 Admin 相关信息")
    @ApiResponse(responseCode = "200", description = "登录失败时，code 返回 401, message 为错误提示信息，data 为空")
    @Operation(summary = "1.1.1 管理员登录接口", tags = {"1.1 Admin 登录/登出"}, operationId = "1.1.1")
    @PostMapping("/login")
    public Result<AdminLoginSuccessVO> login(@Valid @RequestBody AdminLoginDTO dto) {
        // todo 此处会将登录账号和密码打印出来，后续正式上线时，修改此处的日志打印
        log.info("/admin/login, request: {}", JSONObject.toJSONString(dto));
        AdminLoginSuccessVO vo = adminLoginService.loginV2(dto);
        log.info("/admin/login, response: {}", JSONObject.toJSONString(vo));
        return ResultGenerator.genSuccessResult(vo);
    }

    @ApiResponse(responseCode = "200", description = "登出成功时，code 返回 200， data 为空")
    @ApiResponse(responseCode = "200", description = "登出失败时，code 返回 400, message 为错误提示信息")
    @Parameter(name = "userId", description = "管理员用户 ID", example = "c752804d0cd410267f404dd3f0457a57")
    @Operation(summary = "1.1.2 Admin 登出接口", tags = {"1.1 Admin 登录/登出"}, operationId = "1.1.2")
    @GetMapping("/logout")
    public Result<Void> logout(@RequestParam String userId) {
        log.info("/admin/logout, userId: {}", userId);
        // 退出登录时，将redis中缓存的 userId，token 删除
        redisTemplate.delete(userId);
        return ResultGenerator.genSuccessResult();
    }
}
